<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 1. 二分查找的代码
        // [left, right] 左闭右闭
        var search = function(nums, target) {
            let left = 0;
            let right = nums.length - 1;
            let mid;
            // 这里要写成left <= right，因为left和right相等是有效的
            while (left <= right) {
                // 位运算，防止大数溢出, >>1表示right-left的值在整体‘有符号右移’1位，表示除2，向下取整
                mid = left + ((right - left) >> 1)
                // right要赋值为mid-1，因为右区间是闭合
                if (nums[mid] > target) {
                    right = mid - 1
                } else if (nums[mid] < target) {
                    left = mid + 1
                } else {
                    return mid
                }
            }
            return -1
        };
        // console.log(search([-1, 0, 3, 5, 9, 12], 9));
        console.log(search([5, 7, 7, 8, 8, 10], 8));
    </script>
</body>

</html>